package com.xuchen.zhenyang.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.xuchen.zhenyang.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Base64;

@Slf4j
public final class MyUtils {

    /**
     * 获取用户IP
     * 线上环境是nginx反向代理，增加一层x-real-ip
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 用逗号分隔，获取其中不为unknown的第一个IP作为用户的IP
        if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int i = 0; i < ips.length; i++) {
                if (!ips[i].equals("unknown")) {
                    ip = ips[i];
                    break;
                }
            }
        }
        return ip;
    }

    public static void encrypPassword(SysUser sysUser) {
        String newPassword = new SimpleHash("md5", sysUser.getPassword(), ByteSource.Util.bytes(sysUser.getUserName()), 2).toHex();
        sysUser.setPassword(newPassword);
    }

    /**
     * 将图片的str流转成文件
     *
     * @param str      图片的str
     * @param fileName 文件路径+名
     */
    public static File createFileFromStr(String str, String fileDirStr, String fileName) {
        File fileDir = new File(fileDirStr);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File newFile = new File(fileDirStr + fileName);
        if (!newFile.exists()) {
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String imgString = str.substring(str.indexOf(",") + 1);
        byte[] decode = Base64.getDecoder().decode(imgString);
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(newFile);
            os.write(decode);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(os);
            return newFile;
        }
    }
}
